package com.kid.kidliving.commodity.exception;

import com.kid.common.exception.KidlivingCodeEnum;
import com.kid.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @ResponseBody以json格式返回数据
 * @ControllerAdvice(basePackages = "com.kid.kidliving.commodity.controller")统一接管com.kid.kidliving.commodity.controller包下的controller
 */
@Slf4j
@ControllerAdvice(basePackages = "com.kid.kidliving.commodity.controller")
@ResponseBody
public class KidlivingExceptionControllerAdvice {


    /**
     * 如果com.kid.kidliving.commodity.controller包返回MethodArgumentNotValidException.class异常
     * 即数据校验异常
     * 则由handleValidException()方法处理
     * @return
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public R handleValidException(MethodArgumentNotValidException exception){
        //log.error("数据校验问题{},异常类型{}",exception.getMessage(),exception.getClass());
        BindingResult bindingResult = exception.getBindingResult();
        Map<String, String> map = new HashMap<>();
        bindingResult.getFieldErrors().forEach(fieldError -> {
            map.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        return R.error(KidlivingCodeEnum.INVALID_EXCEPTION.getCode(),KidlivingCodeEnum.INVALID_EXCEPTION.getMsg()).put("data", map);
    }

    /**
     * 编写方法，处理其他没有精确匹配的异常
     * 返回统一信息，方便前端处理
     */
    @ExceptionHandler({Throwable.class})
    public R handleException(Throwable throwable){
        return R.error(KidlivingCodeEnum.UNKNOWN_EXCEPTION.getCode(), KidlivingCodeEnum.UNKNOWN_EXCEPTION.getMsg());
    }
}
